package cn.ivicar.app.resource.customer;

import java.io.InputStream;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.codehaus.plexus.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.servlet.RequestScoped;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;

import cn.com.carsmart.exception.BadRequestException;
import cn.com.carsmart.exception.CarsmartException;
import cn.com.carsmart.exception.InternalErrorException;
import cn.com.carsmart.exception.NotAuthorizedException;
import cn.com.carsmart.exception.util.ExceptionResponseBuilder;
import cn.com.carsmart.sae.annotation.RequiresAuthentication;
import cn.com.carsmart.ws.util.CacheUtil;
import cn.ivicar.app.controller.customer.UserController;
import cn.ivicar.app.controller.sae.CurrentUtil;
import cn.ivicar.app.controller.vehicle.VehicleController;
import cn.ivicar.message.push.controller.NotificationController;
import net.sf.json.JSONObject;

@Path("users")
@RequestScoped
public class CustomerReource {

	private static transient final Logger LOGGER = LoggerFactory.getLogger(CustomerReource.class);

	@Inject
	private UserController userController;
	@Inject
	private VehicleController vehicleController;
	@Inject
	private NotificationController notificationController;

	/**
	 * 短信验证码是否有效
	 * 
	 * @param jsonObject
	 * @return
	 */
	@Path("mobile/effective")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response getCaptcha(JSONObject jsonObject) {
		try {
			if (jsonObject.isEmpty() || jsonObject.isNullObject()) {
				throw new BadRequestException("400", "请求参数不能为空!");
			}

			String mobile = jsonObject.optString("mobile", "");
			String captcha = jsonObject.optString("captcha", "");
			String bizType = jsonObject.optString("bizType", "");

			return CacheUtil.noCache(Response.ok(userController.captchaEffective(mobile, captcha, bizType))).build();
		} catch (NotAuthorizedException e) {
			LOGGER.info("无权访问 :", e);
			return ExceptionResponseBuilder.build(e);
		} catch (BadRequestException e) {
			LOGGER.info("非法请求:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (InternalErrorException e) {
			LOGGER.error("校验验证码异常", e);
			return ExceptionResponseBuilder.build(e);
		} catch (CarsmartException e) {
			LOGGER.error("校验验证码失败,失败原因：", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("校验验证码程序异常,异常原因：", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}

	/**
	 * 手机号是否存在
	 * 
	 * @param jsonObject
	 * @return
	 */
	@Path("mobile/exist")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response existMobile(JSONObject jsonObject) {
		try {
			if (jsonObject.isEmpty() || jsonObject.isNullObject()) {
				throw new BadRequestException("400", "请求参数不能为空!");
			}

			String mobile = jsonObject.optString("mobile", "");

			return CacheUtil.noCache(Response.ok(userController.mobileExist(mobile))).build();
		} catch (NotAuthorizedException e) {
			LOGGER.info("无权访问 :", e);
			return ExceptionResponseBuilder.build(e);
		} catch (BadRequestException e) {
			LOGGER.info("非法请求:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (InternalErrorException e) {
			LOGGER.error("校验手机号异常", e);
			return ExceptionResponseBuilder.build(e);
		} catch (CarsmartException e) {
			LOGGER.error("校验手机号失败,失败原因：", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("校验手机号程序异常,异常原因：", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}

	/**
	 * 用户注册
	 * 
	 * @param jsonObject
	 * @return
	 */
	@Path("register")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response register(JSONObject jsonObject) {
		try {
			if (jsonObject.isEmpty() || jsonObject.isNullObject()) {
				throw new BadRequestException("400", "请求参数不能为空!");
			}

			String mobile = jsonObject.optString("mobile", "");
			String password = jsonObject.optString("password", "");
			String captcha = jsonObject.optString("captcha", "");
			userController.register(mobile, password, captcha);
			return CacheUtil.noCache(Response.ok()).build();
		} catch (BadRequestException e) {
			LOGGER.info("非法请求:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (InternalErrorException e) {
			LOGGER.error("用户注册异常", e);
			return ExceptionResponseBuilder.build(e);
		} catch (CarsmartException e) {
			LOGGER.error("用户注册失败,失败原因：", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("用户注册程序异常,异常原因：", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}

	/**
	 * 用户登录
	 * 
	 * @param jsonObject
	 * @return
	 */
	@Path("login")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response oAuthLogin(JSONObject jsonObject) {
		try {
			if (jsonObject.isEmpty() || jsonObject.isNullObject()) {
				throw new BadRequestException("400", "请求参数不能为空!");
			}

			String mobile = jsonObject.optString("mobile", "");
			String password = jsonObject.optString("password", "");
			return CacheUtil.noCache(Response.ok(userController.oAuthLogin(mobile, password))).build();
		} catch (BadRequestException e) {
			LOGGER.info("非法请求:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (InternalErrorException e) {
			LOGGER.error("用户登录异常", e);
			return ExceptionResponseBuilder.build(e);
		} catch (CarsmartException e) {
			LOGGER.error("用户登录失败,失败原因：", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("用户登录程序异常,异常原因：", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}
	
	/**
	 * 用户登录
	 * 
	 * @param jsonObject
	 * @return
	 */
	@Path("/debug/login")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response debugLogin(JSONObject jsonObject) {
		try {
			if (jsonObject.isEmpty() || jsonObject.isNullObject()) {
				throw new BadRequestException("400", "请求参数不能为空!");
			}

			String mobile = jsonObject.optString("mobile", "");
			//String password = jsonObject.optString("password", "");
			return CacheUtil.noCache(Response.ok(userController.debugLogin(mobile))).build();
		} catch (BadRequestException e) {
			LOGGER.info("非法请求:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (InternalErrorException e) {
			LOGGER.error("用户登录异常", e);
			return ExceptionResponseBuilder.build(e);
		} catch (CarsmartException e) {
			LOGGER.error("用户登录失败,失败原因：", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("用户登录程序异常,异常原因：", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}

	/**
	 * 用户退出
	 * 
	 * @param jsonObject
	 * @return
	 */
	@RequiresAuthentication
	@Path("logout")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response logout() {
		try {

			Long customerId = CurrentUtil.getCustomerId();
			userController.logout(customerId);
			return CacheUtil.noCache(Response.ok()).build();
		} catch (BadRequestException e) {
			LOGGER.info("非法请求:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (InternalErrorException e) {
			LOGGER.error("用户退出异常", e);
			return ExceptionResponseBuilder.build(e);
		} catch (CarsmartException e) {
			LOGGER.error("用户退出失败,失败原因：", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("用户退出程序异常,异常原因：", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}

	/**
	 * 修改密码
	 * 
	 * @param jsonObject
	 * @return
	 */
	@RequiresAuthentication
	@Path("password")
	@PUT
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response updatePwd(JSONObject jsonObject) {
		try {
			if (jsonObject.isEmpty() || jsonObject.isNullObject()) {
				throw new BadRequestException("400", "请求参数不能为空!");
			}

			String oldPwd = jsonObject.optString("oldPassword");
			String newPwd = jsonObject.optString("newPassword");
			String newPwdRepeat = jsonObject.optString("repeatPassword");
			Long customerId = CurrentUtil.getCustomerId();
			userController.updatePwd(customerId, oldPwd, newPwd, newPwdRepeat);
			return CacheUtil.noCache(Response.ok()).build();
		} catch (NotAuthorizedException e) {
			LOGGER.info("无权访问 :", e);
			return ExceptionResponseBuilder.build(e);
		} catch (BadRequestException e) {
			LOGGER.info("非法请求:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (InternalErrorException e) {
			LOGGER.error("修改密码异常", e);
			return ExceptionResponseBuilder.build(e);
		} catch (CarsmartException e) {
			LOGGER.error("修改密码失败,失败原因：", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("修改密码程序异常,异常原因：", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}

	/**
	 * 修改/重置密码
	 */
	@Path("password/reset")
	@PUT
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response password(JSONObject object) {
		try {
			if (object == null) {
				throw new BadRequestException("common", "请求参数不能为空！");
			}

			String mobile = object.optString("mobile", "");
			String password = object.optString("newPassword", "");
			String captcha = object.optString("captcha", "");

			boolean flag = userController.resetPasswordByCode(mobile, password, captcha);

			JSONObject obj = new JSONObject();
			obj.put("flag", flag);
			return CacheUtil.noCache(Response.ok(obj)).build();

		} catch (BadRequestException e) {
			LOGGER.info("非法请求:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (InternalErrorException e) {
			LOGGER.error("重置密码数据库查询异常", e);
			return ExceptionResponseBuilder.build(e);
		} catch (CarsmartException e) {
			LOGGER.error("重置密码数据查询失败,失败原因：", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("重置密码程序异常,异常原因：", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}

	/**
	 * 修改手机号
	 */
	@RequiresAuthentication
	@Path("mobile")
	@PUT
	@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response modifyMobile(JSONObject param) {
		try {

			if (param.isEmpty() || param.isNullObject()) {
				throw new BadRequestException("400", "请求参数不能为空!");
			}
			LOGGER.info("修改手机号接口参数param = " + param.toString());
			Long customerId = CurrentUtil.getCustomerId();
			String oldMobile = CurrentUtil.getUserInfo().getMobile();
			String newMobile = param.optString("mobile", "");
			String password = param.optString("password", "");
			String captcha = param.optString("captcha", "");
			userController.modifyMobileByCodeAndPassword(customerId, oldMobile, newMobile, password, captcha);

			return CacheUtil.noCache(Response.ok()).build();
		} catch (NotAuthorizedException e) {
			LOGGER.info("无权访问 :", e);
			return ExceptionResponseBuilder.build(e);
		} catch (BadRequestException e) {
			LOGGER.info("非法请求:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (InternalErrorException e) {
			LOGGER.error("修改手机号添加活动码异常", e);
			return ExceptionResponseBuilder.build(e);
		} catch (CarsmartException e) {
			LOGGER.error("修改手机号添加活动码异常：", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("修改手机号添加活动码异常：", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}

	/**
	 * 请求个人信息
	 */
	@RequiresAuthentication
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response getCustomerInformation() {
		try {
			Long customerId = CurrentUtil.getCustomerId();
			JSONObject obj = userController.getCustomerInfo(customerId);
			return Response.ok(obj).build();
		} catch (NotAuthorizedException e) {
			LOGGER.info("无权访问", e);
			return ExceptionResponseBuilder.build(e);
		} catch (BadRequestException e) {
			LOGGER.info("非法请求:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (InternalErrorException e) {
			LOGGER.error("请求个人信息数据库查询异常", e);
			return ExceptionResponseBuilder.build(e);
		} catch (CarsmartException e) {
			LOGGER.error("请求个人信息数据查询失败,失败原因：", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("请求个人信息程序异常,异常原因：", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}

	/**
	 * 修改个人信息
	 */
	@RequiresAuthentication
	@PUT
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response update(JSONObject jsonObject) {
		try {
			if (jsonObject == null) {
				throw new BadRequestException("400", "请求参数不能为空!");
			}

			Long customerId = CurrentUtil.getCustomerId();
			userController.modifyCustomerInfo(jsonObject, customerId);
			return CacheUtil.noCache(Response.ok()).build();
		} catch (NotAuthorizedException e) {
			LOGGER.info("无权访问", e);
			return ExceptionResponseBuilder.build(e);
		} catch (BadRequestException e) {
			LOGGER.info("非法请求:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (InternalErrorException e) {
			LOGGER.error("修改个人信息数据库查询异常", e);
			return ExceptionResponseBuilder.build(e);
		} catch (CarsmartException e) {
			LOGGER.error("修改个人信息数据查询失败,失败原因：", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("修改个人信息程序异常,异常原因：", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}

	/**
	 * 上传个人头像
	 */
	@RequiresAuthentication
	@Path("head")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Consumes(MediaType.MULTIPART_FORM_DATA + ";charset=utf-8")
	public Response uploadHeadImage(@FormDataParam("data") InputStream data,
			@FormDataParam("data") FormDataContentDisposition fileInfo) {
		try {
			Long customerId = CurrentUtil.getCustomerId();
			JSONObject obj = userController.uploadHeadImage(customerId, data, fileInfo);
			return CacheUtil.noCache(Response.ok(obj)).build();
		} catch (NotAuthorizedException e) {
			LOGGER.info("上传头像错误：", e);
			return ExceptionResponseBuilder.build(e);
		} catch (BadRequestException e) {
			LOGGER.info("上传头像错误：", e);
			return ExceptionResponseBuilder.build(e);
		} catch (CarsmartException e) {
			LOGGER.error("上传头像错误：", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("上传头像错误：", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}

	/**
	 * 解除用户共享
	 * 
	 * @return
	 */
	@RequiresAuthentication
	@PUT
	@Path("{vehicleId}/unshare")
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response unUsershare(@PathParam("vehicleId") String vehicleIdStr) {
		try {
			if (StringUtils.isBlank(vehicleIdStr)) {
				throw new BadRequestException("400", "请求参数不能为空!");
			}
			Long vehicleId = Long.valueOf(vehicleIdStr);
			Long customerId = CurrentUtil.getCustomerId();
			vehicleController.unUsershare(customerId, vehicleId);
			return CacheUtil.noCache(Response.ok()).build();
		} catch (NotAuthorizedException e) {
			LOGGER.info("解除用户共享出错:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (BadRequestException e) {
			LOGGER.info("解除用户共享出错:" + e.getMessage());
			return ExceptionResponseBuilder.build(e);
		} catch (InternalErrorException e) {
			LOGGER.error("解除用户共享出错:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (CarsmartException e) {
			LOGGER.error("解除用户共享出错:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("解除用户共享出错:", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}

	/**
	 * 请求用户共享车辆列表
	 * 
	 * @return
	 */
	@RequiresAuthentication
	@GET
	@Path("vehicles/shares")
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response getUsershareVehicleList() {
		try {
			Long customerId = CurrentUtil.getCustomerId();
			JSONObject result = vehicleController.getUsershareVehicleList(customerId);
			return CacheUtil.noCache(Response.ok(result)).build();
		} catch (NotAuthorizedException e) {
			LOGGER.info("请求用户共享车辆列表出错:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (BadRequestException e) {
			LOGGER.info("请求用户共享车辆列表出错:" + e.getMessage());
			return ExceptionResponseBuilder.build(e);
		} catch (InternalErrorException e) {
			LOGGER.error("请求用户共享车辆列表出错:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (CarsmartException e) {
			LOGGER.error("请求用户共享车辆列表出错:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("请求用户共享车辆列表出错:", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}
	
	@RequiresAuthentication
	@Path("notification/register")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response notificationRegister(JSONObject jsonObject) {
		try {
			if (jsonObject.isEmpty() || jsonObject.isNullObject()) {
				throw new BadRequestException("400", "请求参数不能为空!");
			}

			Long appId = jsonObject.optLong("appId");
			if(appId == null || appId.intValue() ==0){
				throw new BadRequestException("400", "请输入appId!");
			}
			Long customerId = CurrentUtil.getCustomerId();
			String clientId = jsonObject.optString("clientId", "");
			if(StringUtils.isBlank(clientId)){
				throw new BadRequestException("400", "请输入clientId!");
			}
			String clientType = jsonObject.optString("clientType", "");
			if(StringUtils.isBlank(clientType)){
				throw new BadRequestException("400", "请输入clientType!");
			}
			
			notificationController.register(appId, customerId, clientId, clientType);
			return CacheUtil.noCache(Response.ok()).build();
		} catch (BadRequestException e) {
			LOGGER.info("注册消息提醒出错:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (InternalErrorException e) {
			LOGGER.error("注册消息提醒出错:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (CarsmartException e) {
			LOGGER.error("注册消息提醒出错:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("注册消息提醒出错:", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}
	
	@RequiresAuthentication
	@Path("notification/logout")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response notificationLogout(JSONObject jsonObject) {
		try {
			if (jsonObject.isEmpty() || jsonObject.isNullObject()) {
				throw new BadRequestException("400", "请求参数不能为空!");
			}

			Long appId = jsonObject.optLong("appId");
			if(appId == null || appId.intValue() ==0){
				throw new BadRequestException("400", "请输入appId!");
			}
			Long customerId = CurrentUtil.getCustomerId();
			String clientId = jsonObject.optString("clientId", "");
			if(StringUtils.isBlank(clientId)){
				throw new BadRequestException("400", "请输入clientId!");
			}
			String clientType = jsonObject.optString("clientType", "");
			if(StringUtils.isBlank(clientType)){
				throw new BadRequestException("400", "请输入clientType!");
			}
			
			notificationController.logout(appId, customerId, clientId, clientType);
			return CacheUtil.noCache(Response.ok()).build();
		} catch (BadRequestException e) {
			LOGGER.info("注册消息提醒出错:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (InternalErrorException e) {
			LOGGER.error("注册消息提醒出错:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (CarsmartException e) {
			LOGGER.error("注册消息提醒出错:", e);
			return ExceptionResponseBuilder.build(e);
		} catch (Exception e) {
			LOGGER.error("注册消息提醒出错:", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}
	
	@RequiresAuthentication
	@Path("token/effective")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public Response getCaptcha() {
		try {
			boolean effective = true;
			try {
				CurrentUtil.getCustomerId();
			} catch (Exception e) {
				effective = false;
				e.printStackTrace();
			}
			JSONObject result = new JSONObject();
			result.put("effective", effective);

			return CacheUtil.noCache(Response.ok(result)).build();
		} catch (Exception e) {
			LOGGER.error("校验用户token程序异常,异常原因：", e);
			return ExceptionResponseBuilder.build(new InternalErrorException(e));
		}
	}
}